package cz.cernilovsky.android.profileapp.services;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import android.app.PendingIntent;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationClient.OnAddGeofencesResultListener;
import com.google.android.gms.location.LocationClient.OnRemoveGeofencesResultListener;

import cz.cernilovsky.android.profileapp.R;
import cz.cernilovsky.android.profileapp.model.Location;

public class AddGeofence implements ConnectionCallbacks, OnConnectionFailedListener, OnAddGeofencesResultListener{
	private static final String TAG = "AddGeofence";
	private Location location;
	private LocationClient c;
	private Context context;
	
	public static void addLocation(Location location, Context context) {
		new AddGeofence(location, context);
	}
	
	private AddGeofence(Location location, Context context) {
		this.location = location;
		this.context = context;
		c = new LocationClient(context, this, this);
		c.connect();
		Log.d(TAG, "AddGeofence");
	}

	@Override
	public void onConnectionFailed(ConnectionResult arg0) {
		NotificationService.notify(context, R.string.error_location_service_disconnected, R.string.error);
		Log.d(TAG, "onConnectionFailed");
	}

	@Override
	public void onConnected(Bundle arg0) {
		List<Geofence> geofences = new ArrayList<Geofence>();
		geofences.add(Location.toGeofence(location, new Geofence.Builder()));
		c.addGeofences(geofences, ProfileProcessor.getPendingIntent(context), this);
		Log.d(TAG, "onConnected");
	}

	@Override
	public void onDisconnected() {
		NotificationService.notify(context, R.string.error_location_service_disconnected, R.string.error);
		Log.d(TAG, "onDisconnected");
	}

	@Override
	public void onAddGeofencesResult(int statusCode, String[] geofenceRequestIDs) {
		ToastService.toast(context, context.getString(R.string.location_added) + ": " + location.getName());
		//Preferences.addLocationID(context, geofenceRequestIDs[0]);
		NotificationService.mainNotification(context);
		c.disconnect();
		Log.d(TAG, "onAddGeofencesResult");
	}

}
